package com.eclink.iot.tcpserver;

import com.alibaba.fastjson.JSONObject;
import com.eclink.iot.DeviceOnlineStatusListener;
import com.eclink.iot.mqtt.MqttManager;
import com.eclink.iot.rfid.Antenna;
import com.eclink.iot.rfid.RFIDDevice;
import com.eclink.iot.rfid.RFIDServer;
import com.eclink.iot.rfid.RFIDTagDataListener;
import com.eclink.iot.tcpserver.domain.business.DeviceWebsocketSession;
import com.eclink.iot.tcpserver.entity.DeviceStatusDTO;
import com.eclink.iot.tcpserver.websocket.RFIDWebSocketServer;
import com.eclink.iot.tcpserver.websocket.WebSocketServer;
import jakarta.websocket.Session;

import java.util.Collection;


public class RFIDServerManager {

    private static final DeviceOnlineStatusListener device_online_status_listener = (uuid, status) -> {

        for(Session session: WebSocketServer.sessions) {
            DeviceStatusDTO dto = new DeviceStatusDTO();
            dto.setUuid(uuid);
            dto.setStatus(status);
            String data = JSONObject.toJSONString(dto);
            session.getAsyncRemote().sendText(data);
        }

        System.out.println("device_online_status_listener => uuid: " + uuid + ", status: " + status);
    };

    public static Collection<RFIDDevice> getOnlineDevices() {
        return RFIDServer.get_online_devices();
    }

    public static boolean isDeviceActive(String uuid) {
        return RFIDServer.isDeviceActive(uuid);
    }

    public static void inventory(String uuid) {
        Collection<RFIDDevice> onlineDevices = RFIDServer.get_online_devices();
        for (RFIDDevice device : onlineDevices) {
            if (device.getUuid().equals(uuid)) {
                boolean status = RFIDServer.inventory_multi(device.getUuid(),
                        Antenna.NO1 | Antenna.NO2 | Antenna.NO3 | Antenna.NO4);
                System.out.println("inventory status: " + status);
            }
        }
    }

    public static void stopInventory() {

        Collection<RFIDDevice> onlineDevices = RFIDServer.get_online_devices();
        for (RFIDDevice device : onlineDevices) {
            boolean status = RFIDServer.stop(device.getUuid());
            System.out.println("inventory status: " + status);
        }
    }

    public static void startRFIDServer() {

        RFIDServer.initialization(8087);
        RFIDServer.set_rfid_tag_data_listener((uuid, ant, epc)->{
            MqttManager.publish("device/"+uuid+"/tag", epc);
        });
        RFIDServer.set_device_online_status_listener(device_online_status_listener);

    }

}
